package com.zero.common.datasource;

import java.util.Random;

import org.springframework.util.Assert;

public class DataSourceSwitcher {
	@SuppressWarnings("rawtypes")
	private static final ThreadLocal contextHolder = new ThreadLocal();
	
	private static int slaveno = 0;

	@SuppressWarnings("unchecked")
	public static void setDataSource(String dataSource) {
	Assert.notNull(dataSource, "数据源不能为空！");
		contextHolder.set(dataSource);
	}

	public static void setMaster() {
		clearDataSource();
	}

	public static void setSlave() {
		Random random = new Random();
		int no = random.nextInt(slaveno);
		setDataSource("slave_"+no);
	}

	public static void setSlaveno(int slaveno) {
		DataSourceSwitcher.slaveno = slaveno;
	}

	public static String getDataSource() {
		return (String) contextHolder.get();
	}

	public static void clearDataSource() {
		contextHolder.remove();
	}
}